package com.hooware.controller;

import com.hooware.domain.Role;
import com.hooware.domain.UserInfo;
import com.hooware.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/findAll.do")
    public String findAll(Model model) {
        List<UserInfo> userInfoList = userService.findAll();
        model.addAttribute("userList", userInfoList);
        System.out.println("=============查询所有用户==========: " + userInfoList);
        return "user-list";
    }

    @RequestMapping("/save.do")
    public String save(UserInfo userInfo) {
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
        userService.saveUser(userInfo);
        System.out.println("=============保存用户==========: " + userInfo);
        return "redirect:findAll.do";
    }

    @RequestMapping("/findById.do")
    public ModelAndView findById(Model model, String id) {
        ModelAndView mav = new ModelAndView("user-show");
        UserInfo userInfo = userService.findById(id);
        model.addAttribute("user", userInfo);
        System.out.println("=============findById用户========== id: " + id);
        return mav;
    }

    @RequestMapping("/findUserByIdAndAllRole.do")
    public String findUserByIdAndAllRole(Model model, String id) {
        UserInfo userInfo = userService.findById(id);
        List<Role> roleList = userService.findOtherRoles(id);
        model.addAttribute("user", userInfo);
        model.addAttribute("roleList", roleList);
        System.out.println("=============findUserByIdAndAllRole用户========== id: " + id);
        return "user-role-add";
    }


    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId", required = true) String userId, @RequestParam(name = "ids", required = true) String[] ids) {
        userService.addRoleToUser(userId, ids);
        System.out.println("=============addRoleToUser用户========== id: " + userId + "/ " + Arrays.toString(ids));
        return "redirect:findAll.do";
    }
}
